<script setup lang="ts">
import type { Page } from '@/types'
import { dateFormat, getFormatDictMap } from '@/util/dict'
import { defineAsyncComponent, onMounted, ref } from 'vue'
import { Search, Refresh, Finished } from '@/util/icons'
import Pagination from '@/components/Pagination.vue'
import type { LogTable } from '@/types/log'
import AuthButton from '@/components/AuthButton.vue'
import AuthLink from '@/components/AuthLink.vue'
import { getLogHandle, getLogSign } from './api'
import type { Sort } from 'element-plus'
const props = defineProps<{
  type: 'sign' | 'handle'
}>()
// 菜单名称
const pageN = '日志'
const page = ref<Page<LogTable>>({
  num: 1,
  size: 10,
  rows: [],
  count: 0
})
/* 获取对应的字典信息 */
const tableDict = ref<Map<string, string>>()
// 页面加载
const loading = ref<boolean>(false)
// 搜索数据

const searchForm = ref<LogTable>({
  time: '',
  username: '',
  hid: []
})
let order = ''
// 获取页面数据
function getPageData() {
  loading.value = true
  if (props.type == 'handle') {
    getLogHandle(page.value, searchForm.value, order)
      .then((tabs) => {
        page.value = tabs.data
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false
        }, 500)
      })
  } else if (props.type == 'sign') {
    getLogSign(page.value, searchForm.value, order)
      .then((tabs) => {
        page.value = tabs.data
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false
        }, 500)
      })
  }
}
onMounted(() => {
  getFormatDictMap('sys_log_manage', 'head').then((d) => {
    tableDict.value = d
  })
  getPageData()
})

/* 搜索 */
/* 是否展示搜索栏 */
const showSearchBar = ref<boolean>(true)

// 重置搜索框
function reSearch() {
  searchForm.value = {
    time: '',
    username: '',
    hid: []
  }
  getPageData()
}
/* 对话框控制 */
const dialogVisible = ref<boolean>(false)
const dialogWidth = ref<string>('50%')
/* 选择器 */
const selectData = ref<LogTable[]>([])
function onSelect(data: LogTable[]) {
  selectData.value = data
}
const delData = ref<LogTable[]>([])
/* 控制器 */
const controlType = ref<'none' | 'del' | 'preview' | 'export' | 'selectHandle'>('none')
// 标题
const dialogTitle = ref('')
// 删除控制
const Del = defineAsyncComponent(() => import('./Del.vue'))
function del(rows: LogTable[]) {
  controlType.value = 'del'
  dialogTitle.value = `你确定要删除以下${pageN}吗?`
  dialogWidth.value = '80%'
  delData.value = rows
  dialogVisible.value = true
}
// 日志导出处理
const ExportView = defineAsyncComponent(() => import('./ExportView.vue'))
function getOut() {
  controlType.value = 'export'
  dialogTitle.value = `日志导出`
  dialogWidth.value = '40%'
  dialogVisible.value = true
}

// 日志详情
const LogPreView = defineAsyncComponent(() => import('./LogPreView.vue'))
const PreViewData = ref<LogTable>()
function preView(data: LogTable) {
  controlType.value = 'preview'
  dialogTitle.value = `详情`
  dialogWidth.value = '40%'
  PreViewData.value = data
  dialogVisible.value = true
}

// 接口查询赛选
const HandleSelect = defineAsyncComponent(() => import('./HandleSelect.vue'))
function selectHandle() {
  controlType.value = 'selectHandle'
  dialogTitle.value = `筛选接口`
  dialogWidth.value = '80%'
  dialogVisible.value = true
}

function selectCbk(hids: number[]) {
  dialogVisible.value = false
  searchForm.value.hid = hids
  getPageData()
}
/**
 * 测试
 */
function test(e: any) {
  console.log(e)
}

/**
 * 排序
 */
function onSort(e: Sort) {
  if (e.prop == 'time') {
    switch (e.order) {
      case 'ascending':
        order = 'asc'
        break
      case 'descending':
        order = 'desc'
        break
      default:
        order = e.order
    }
  }
  getPageData()
}
</script>

<template>
  <div class="page-root">
    <div class="control">
      <div class="search" v-show="showSearchBar">
        <el-form :inline="true">
          <el-form-item class="date-picker" :label="tableDict?.get('time') || 'time'">
            <el-date-picker
              v-model="searchForm.time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="HH:mm:ss"
              width="100px"
            />
          </el-form-item>
          <el-form-item :label="tableDict?.get('username') || 'username'">
            <el-input
              v-model="searchForm.username"
              :placeholder="'请输入' + tableDict?.get('username') || 'username'"
            ></el-input>
          </el-form-item>
          <el-form-item :label="tableDict?.get('handleName') || 'handleName'">
            <el-button @click="selectHandle" :icon="Finished">
              {{ (searchForm.hid as number[]).length > 0 ? '查看筛选' : '筛选接口' }}
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="getPageData">搜索</el-button>
            <el-button :icon="Refresh" @click="reSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="ctl-bts">
        <span class="ctl-l">
          <AuthButton
            @click="del(selectData)"
            :disabled="selectData.length == 0"
            auth-tag="sys:log:del"
          />
          <AuthButton @click="" auth-tag="sys:log:clear" />
          <AuthButton @click="getOut" auth-tag="sys:log:export" />
        </span>
        <span class="ctl-r">
          <el-button :icon="Search" circle @click="showSearchBar = !showSearchBar"></el-button>
          <el-button :icon="Refresh" @click="getPageData" circle></el-button>
        </span>
      </div>
    </div>
    <div class="ctx">
      <el-table
        v-loading="loading"
        table-layout="auto"
        :stripe="true"
        :data="page.rows"
        @sort-change="onSort"
        height="100%"
        :flexible="true"
        @selection-change="onSelect"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="username" align="center">
          <template #header>
            {{ tableDict?.get('username') || 'username' }}
          </template>
          <template #default="{ row }">
            <span class="highlight-success">{{ row['username'] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="handleName" align="center">
          <template #header>
            {{ tableDict?.get('handleName') || 'handleName' }}
          </template>
        </el-table-column>
        <el-table-column prop="key" align="center">
          <template #header>
            {{ tableDict?.get('key') || 'key' }}
          </template>
          <template #default="{ row }">
            <span class="highlight-info">{{ row['key'] }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="path" align="center">
          <template #header>
            {{ tableDict?.get('path') || 'path' }}
          </template>
          <template #default="{ row }">
            <span class="highlight-info">{{ row['path'] }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="time" align="center">
          <template #header>
            {{ tableDict?.get('time') || 'time' }}
          </template>
          <template #default="{ row }">
            <span class="highlight-info">{{ dateFormat(row['time']) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ip" align="center">
          <template #header>
            {{ tableDict?.get('ip') || 'ip' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" align="center">
          <template #header>
            {{ tableDict?.get('status') || 'status' }}
          </template>
          <template #default="{ row }">
            <el-tag :type="row['status'] > 400 ? 'danger' : 'success'">{{ row['status'] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header> 操作 </template>
          <template #default="{ row }">
            <div class="buttons">
              <el-link @click="preView(row)">详情</el-link>
              <AuthLink auth-tag="sys:log:del" @click="del([row])"></AuthLink>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page="page" :get-page-data="getPageData" />
    </div>
    <el-dialog
      @closed="controlType = 'none'"
      :width="dialogWidth"
      v-model="dialogVisible"
      :title="dialogTitle"
    >
      <Del
        v-if="controlType == 'del'"
        :refresh="getPageData"
        :table-head-dict-map="tableDict!"
        :rows="delData"
        @c-dlg="dialogVisible = false"
      />
      <LogPreView
        v-else-if="controlType == 'preview'"
        @c-dlg="dialogVisible = false"
        :log-info="PreViewData!"
        :t-dict="tableDict!"
      />
      <ExportView
        v-else-if="controlType == 'export'"
        :t-dict="tableDict!"
        :cdn="searchForm"
        :type="type"
      />
      <HandleSelect
        v-else-if="controlType == 'selectHandle'"
        :type="type"
        @select-handle="selectCbk"
        :ids="searchForm.hid as number[]"
      />
    </el-dialog>
  </div>
</template>
<style scoped lang="less">
@import '../../../assets/page_bgl.less';
</style>
